package sort;

import java.util.Arrays;

public class GuiBingSort {

    public int[] sortArray(int[] nums) {
        int length = nums.length;
        int[] tempNums = new int[length];
        msort(nums,tempNums,0,length-1);
        return tempNums;
    }

    public void msort(int[] nums, int[] tempNums, int left, int right) {
        if (left<right){
            int mid=(left+right)/ 2;
            msort(nums, tempNums, left, mid);  //递归划分左半部分
            msort(nums, tempNums, mid+1, right); //递归划分右半部分
            merge(nums,tempNums,left,mid,right);
        }
    }


    public void  merge(int[] nums, int[] tempNums,int left,int mid, int right ){
          int l_pos=left;
          int r_pos=mid+1;
          int  pos=left;
          while (l_pos<=mid &&r_pos<=right){
              if (nums[l_pos]<nums[r_pos]){
                  tempNums[pos++]=nums[l_pos++];
              }
              else {
                  tempNums[pos++]=nums[r_pos++];
              }

          }

          while (l_pos<=mid){
              tempNums[pos++]=nums[l_pos++];
          }
          while (r_pos<=right){
              tempNums[pos++]=nums[r_pos++];
          }

//          if (pos>=nums.length){
//              nums = Arrays.copyOf(tempNums, tempNums.length);
//          }
//
//        return nums;
    }

    public static void main(String[] args) {
        GuiBingSort guiBingSort = new GuiBingSort();
        int[] ints = guiBingSort.sortArray(new int[]{5, 8, 2, 4, 1, 7});
        for (int a:
                ints
             ) {
            System.out.println(a);
        }
    }
}
